package ChaiPiao;

import java.util.ArrayList;
import java.util.List;

public abstract class AbstractListEnumerable<SOURCE_TYPE, RESULT_TYPE> implements Enumerable<RESULT_TYPE> {
    protected List<SOURCE_TYPE> sourceList;
    protected boolean isEnumOver = false;
    protected int length = 0;
    protected int currentIndex = 0;
    protected RESULT_TYPE currentResult;
    //get set


    public AbstractListEnumerable() {
        sourceList = new ArrayList<>();
    }

    public boolean isEnumOver() {
        return isEnumOver;
    }

    protected abstract RESULT_TYPE source2result(SOURCE_TYPE source);

    private void freshLength() {
        this.length = sourceList.size();
    }

    public void addSource(SOURCE_TYPE source) {
        this.sourceList.add(source);
        this.freshLength();
    }

    public void removeSource(SOURCE_TYPE source) {
        this.sourceList.remove(source);
        this.freshLength();
    }

    public void clearSource() {
        this.sourceList.clear();
        this.freshLength();
    }

    public RESULT_TYPE enumeration() {
        if (this.currentIndex >= this.length) {
            this.isEnumOver = true;
            return null;
        }
        SOURCE_TYPE s = this.sourceList.get(this.currentIndex);
        this.currentIndex++;
        this.currentResult = source2result(s);
        return currentResult;
    }

    @Override
    public void reset() {
        this.currentIndex = 0;
        this.isEnumOver = false;
    }

    @Override
    public RESULT_TYPE getCurrent() {
        return currentResult;
    }
}
